package com.zycfc.zsf.boot.util.ead;

import org.apache.commons.codec.binary.*;
import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
import org.slf4j.*;

public class DES3Utils
{
    private static final Logger log;
    private static final String KEY_ALGORITHM = "DESede";
    private static final String DEFAULT_CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
    
    public static String encrypt(final String str, final String key) {
        try {
            final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            final byte[] byteContent = str.getBytes("utf-8");
            cipher.init(1, getSecretKey(key));
            final byte[] result = cipher.doFinal(byteContent);
            return Base64.encodeBase64String(result);
        }
        catch (Exception ex) {
            DES3Utils.log.error("\u52a0\u5bc6\u5931\u8d25", (Throwable)ex);
            return null;
        }
    }
    
    public static String decrypt(final String str, final String key) {
        try {
            final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(2, getSecretKey(key));
            final byte[] result = cipher.doFinal(Base64.decodeBase64(str));
            return new String(result, "utf-8");
        }
        catch (Exception ex) {
            DES3Utils.log.error("\u89e3\u5bc6\u5931\u8d25", (Throwable)ex);
            return null;
        }
    }
    
    private static SecretKeySpec getSecretKey(final String key) {
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance("DESede");
            kg.init(new SecureRandom(key.getBytes()));
            final SecretKey secretKey = kg.generateKey();
            return new SecretKeySpec(secretKey.getEncoded(), "DESede");
        }
        catch (NoSuchAlgorithmException ex) {
            DES3Utils.log.error("\u751f\u6210\u52a0\u5bc6\u79d8\u94a5", (Throwable)ex);
            return null;
        }
    }
    
    public static void main(final String[] args) {
        final String content = "zycfc1234";
        final String key = "key";
        System.out.println("content:" + content);
        final String s1 = encrypt(content, key);
        System.out.println("\u52a0\u5bc6:" + s1);
        System.out.println("\u89e3\u5bc6:" + decrypt(s1, key));
    }
    
    static {
        log = LoggerFactory.getLogger((Class)DES3Utils.class);
    }
}
